package com.yc.spring.jdbc.bank.dao;

import com.yc.spring.jdbc.bank.bean.Account;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class AccountDao {

    @Resource
    JdbcTemplate jdbc;

    public int insert(long id, String pwd, double money) {
        String sql = "insert into account values(?,?,?)";
        return jdbc.update(sql, id, pwd, money);
    }

    public Account selectById(long id) {
        String sql = "select * from account where accountid = ?";
        return jdbc.queryForObject(sql, new RowMapper<Account>() {
            @Override
            public Account mapRow(ResultSet rs, int rowNum) throws SQLException {
                Account account = new Account();
                account.setId(rs.getLong("accountid"));
                account.setPwd(rs.getString("password"));
                account.setBalance(rs.getDouble("balance"));
                return account;
            }
        }, id);
    }

    public int update(long id, double money) {
        String sql = "update account set balance=balance + ? where accountid=?";
        return jdbc.update(sql, money, id);
    }

}
